﻿@namespace LaserMark.Components
@using LaserMark.DataAccess.Service

<div class="@ClassString()">
    <div class="@ClassString1()"></div>
    @foreach (var item in StrList1)
    {
        <div class="col-6">
            <BootstrapInputNumber DisplayText="@item.Name" @bind-Value="item.GOrder" ShowLabel="true"></BootstrapInputNumber>
        </div>
    }
</div>

<ShowLayout Order="@Order"></ShowLayout>
<DialogFooter OnSave="@OnSave">
    <BodyTemplate>
        <Button Icon="fa-solid fa-eye" Text="显示排版" OnClick="OnChange"></Button>
    </BodyTemplate>
</DialogFooter>

@code {
    private string ClassString()
    {
        return CssBuilder.Default("g_order row g-3 form-inline")
        .Build()!;
    }

    private string ClassString1()
    {
        return CssBuilder.Default()
        .AddClass("is_layout", Order != null)
        .Build()!;
    }

    [Inject]
    [NotNull]
    private IGCodeOrderService? GCodeOrderService { get; set; }

    [Inject]
    [NotNull]
    private ISecretService? SecretService { get; set; }

    [NotNull]
    private List<GCodeOrder>? StrList1 { get; set; } = new();

    [NotNull]
    private string[]? Order { get; set; }


    private bool FirstRender { get; set; }

    protected override async Task OnInitializedAsync()
    {
        await base.OnInitializedAsync();

        StrList1 = await GCodeOrderService.GetAll() ?? new();
    }

    private async Task<bool> OnSave(string password)
    {
        var res = await SecretService.GetSecret("Customer", password);
        if (res)
        {
            await GCodeOrderService.UpdateBatch(StrList1);
            return true;
        }
        else
        {
            return false;
        }
    }

    private async Task OnChange()
    {
        OpenFileDialog dialog = new OpenFileDialog();
        dialog.InitialDirectory = $@"{AppContext.BaseDirectory}";
        dialog.Filter = "g代码|*.g";
        var result = dialog.ShowDialog();

        if (result!.Value)
        {
            Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
            using (var stream = new StreamReader(dialog.FileName,Encoding.GetEncoding("GB2312")))
            {
                while (stream.Peek() != -1)
                {
                    var line = await stream.ReadLineAsync();

                    if (line != null && line.Contains("P4001"))
                    {
                        var separator = line.IndexOf('=');

                        var key = line.Substring(0, separator);
                        var value = line.Substring(separator + 1);

                        var arr = value.Split("_");
                        Order = arr;
                        break;
                    }
                }
            }
        }
    }
}
